﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using OfficeOpenXml;
using System.IO;

/// <summary>
///Util 的摘要说明
/// </summary>
public class Util
{
	public Util()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    public static void ExportExcel(DataView dv,string fileName,string sheetName) {
        ExcelPackage pck = new ExcelPackage();

        //Add a worksheet.
        var ws = pck.Workbook.Worksheets.Add(sheetName);

        for (int i = 0; i < dv.Table.Columns.Count; i++)
        {
            ws.Cells[1, i + 1].Value = dv.Table.Columns[i].ColumnName;
        }

        for (int i = 0; i < dv.Count; i++)
        {
            for (int j = 0; j < dv.Table.Columns.Count; j++)
            {
                ws.Cells[i + 2, j + 1].Value = dv[i][j];
            }
        }
        
        //ws.Cells.AutoFitColumns(0);

        fileName = HttpUtility.UrlEncode(fileName);

        pck.SaveAs(HttpContext.Current.Response.OutputStream);
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;  filename=" + fileName);
        HttpContext.Current.Response.End();
    }
    public static void ExportExcel(DataTable dt, string fileName,string sheetName)
    {
        ExcelPackage pck = new ExcelPackage();

        //Add a worksheet.
        var ws = pck.Workbook.Worksheets.Add(sheetName);

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            ws.Cells[1, i + 1].Value = dt.Columns[i].ColumnName;
        }

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                ws.Cells[i + 2, j + 1].Value = dt.Rows[i][j];
            }
        }

        //ws.Cells.AutoFitColumns(0);

        fileName = HttpUtility.UrlEncode(fileName);

        pck.SaveAs(HttpContext.Current.Response.OutputStream);
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;  filename=" + fileName);
        HttpContext.Current.Response.End();
    }
}